//reducer
//初始化状态
import  {ADD_CART,JIAN_CART} from '../actions/types'
let defaultState = {
    carts: [],
    products: [{
        name: "猫粮",
        id: 1000,
        price: 10
    }, {
        name: "狗粮",
        id: 1001,
        price: 20
    }],
   
}
let reducer=(prevState = defaultState, action) => {

    let state = JSON.parse(JSON.stringify(prevState))
    switch (action.type) {
        
        case ADD_CART:
            var curProduct = state.carts.find(item => {
                return item.id === action.product.id
            })
            if (curProduct) {
                curProduct.num++;
                curProduct.total = curProduct.num * curProduct.price
            } else {
                state.carts.push({
                    ...action.product,
                    num: 1,
                    total: action.product.price
                })
            }


            break;
        case JIAN_CART:
            var index = state.carts.indexOf(curProduct = state.carts.find(item => {
                return item.id === action.product.id
            }))
            if (curProduct) {
                if (curProduct.num > 1) {
                    curProduct.num--;
                    curProduct.total = curProduct.num * curProduct.price
                }

            } else {
                state.carts.splice(index, 1)
            }


            break;
        default:

            break;
    }

    return state
}
export default reducer